<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 公用返回函数
 * 200成功
 * 201登录失效
 * 202权限不足
 * 400业务错误
 * 404数据库错误
 * 405签名错误
 * 500其他错误
 * @param int $code 验证码
 * @param string $msg 信息
 * @param array $data 数据
 * @param int $isStop 是否终止操作 0.终止并输出 1.直接返回
 * @param int $browserCode 浏览器状态码
 * @return $this
 */
function ret($code = 200, $msg = '', $data = [], $isStop = 0, $browserCode = 200)
{
    $ret['code'] = $code;
    $ret['msg'] = $msg;
    $ret['data'] = $data;

    $retMsgArr = array(
        '200' => '成功',
        '201' => '登录失效，请重新登录',
        '202' => '登录失效，权限不足',
        '400' => '业务错误',
        '404' => '数据库错误',
        '405' => '签名错误',
        '500' => '其他错误',
    );
    $code = (string)$code;
    $ret['msg'] = empty($msg) ? $retMsgArr[$code] : $msg;

    //判断是否加密
    if (config('app.aes')) {
        $aes = new Aes();
        $ret = $aes->encrypt($ret);
    }

    //返回输出数据
    if ($isStop == 0) {
        echo json_encode($ret);
        die;
    }

//    return json($ret, JSON_UNESCAPED_UNICODE)->code($browserCode);
    return $ret;
}

/**
 * 获取随机数作为验证码
 * @param int $digit 验证码位数
 * @param int $type 验证码类型 1：默认数字 2：字符 3:数字+字符
 * @return string $authnum  返回验证码
 */
function randomStr($digit = 6, $type = 1)
{
    if ($type == 1) {
        $char = "0,1,2,3,4,5,6,7,8,9";
        $x = 9;
    } elseif ($type == 2) {
        $char = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
        $x = 25;
    } else {
        $char = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
        $x = 35;
    }

    $authnum = "";
    $list = explode(",", $char);
    for ($i = 0; $i < $digit; $i++) {
        $randnum = rand(0, $x); // 10+26;
        $authnum .= $list[$randnum];
    }
    return $authnum;
}

/**
 * 获取IP地区(淘宝api)
 * @param string $ip
 * @return string   地区-城市
 */
function get_ip_area($ip)
{
    try {
        $ipInfo = json_decode(file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip), 1);
        if ($ipInfo) {
            if ($ipInfo['data']['region'] == 'XX') {
                return $ipInfo['data']['city'];
            } else {
                return $ipInfo['data']['region'] . '-' . $ipInfo['data']['city'];
            }
        } else {
            return '未知';
        }
    } catch (\Exception $e) {
        return '未知';
    }
}

/**
 * @return string
 * 获取IP
 * 2020年5月5日11:39:31
 * by J.sky
 */
function get_ip()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $cip = $_SERVER['HTTP_CLIENT_IP'];
    } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    } else if (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];
    } else {
        $cip = '';
    }
    preg_match("/[\d\.]{7,15}/", $cip, $cips);
    $cip = isset($cips[0]) ? $cips[0] : 'unknown';
    unset($cips);
    return $cip;
}

/**
 * GET提交
 * @param $url
 * @return mixed
 */
function curlGet($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}

/**
 * POST提交
 * @param $url
 * @param $data (注释： $header[] = 'Content-Type:application/json;charset=utf-8';则传递json后的字符串)
 * @param array $header (头信息)
 * @return mixed
 */
function curlPost($url, $data, $header = array())
{ // 模拟提交数据函数
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //设置头信息
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    //    curl_setopt($curl, CURLOPT_COOKIEFILE, $GLOBALS['cookie_file']); // 读取上面所储存的Cookie信息
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno' . curl_error($curl);
    }
    curl_close($curl); // 关键CURL会话
    return $tmpInfo; // 返回数据
}

/**
 * 日志记录
 * @param $name         操作名称
 * @param $content      操作内容
 * @param $operat       操作者
 * @param $type         日志类型1.操作记录2.信息记录3.报错记录
 * @param $op_type      操作类型
 *
 */
function recordLog($name, $content, $operat, $type, $op_type)
{
    $data['name'] = $name;
    $data['operat'] = $operat;
    $data['type'] = $type;

    //判断日志类型是否存在，如果不存在。记录到其他日志中
    if (!in_array($op_type, config('log.apart_level'))) {
        $data['op_type'] = 'other';
    } else {
        $data['op_type'] = $op_type;
    }

    //转json存入数据库中
    if (is_array($content)) {
        if (is_object($content)) {
            $data['content'] = implode('|', $content->toArray());
        } else {
            $data['content'] = implode('|', $content);
        }
    } else {
        $data['content'] = $content;
    }

    $data['json_content'] = json_encode($content);
    \app\admin\model\Logs::create($data);
    //记录存储时间
    $data['content'] = $content;
    $data['time'] = date('Y-m-d H:i:s', time());
    \think\facade\Log::record($data, $op_type);
}

/**
 * 日志功能
 * by J.sky
 * 2019年12月6日
 * @param $log  log内容   换行符："\r\n"
 * @param $type [日志默认为2  1：报错日志 2:记录  3：操作]
 * @param string $folder 报错路径
 * 路径是"./runtime/log/admin_log/" . $folder . "/";
 */
function rLog($log, $type = 1, $folder = '')
{
    $log_info = is_array($log) ? json_encode($log, JSON_UNESCAPED_UNICODE) : $log;
    $folder = empty($folder) ? retMAC() . '/function' : retMAC() . '/' . $folder;

    if ($type == 1 || empty($type)) {
        $path = "../runtime/error_log/" . $folder . "/";
    } elseif ($type == 2) {
        $path = "../runtime/record_log/";
    } else {
        $path = "../runtime/operate_log/";
    }
    $content = date("Y-m-d H:i:sa") . "\r\n" . $log_info . "\r\n" . "=================================================" . "\r\n";

    // 创建文件夹$path,并给777的权限（所有权限）true;允许创建多级目录
    !is_dir($path) ? mkdir($path, 0777, true) : '';

    $file = $path . date("Y-m-d") . '.txt';    // 写入的文件
    $fp = fopen($file, "a");//打开文件资源通道 不存在则自动创建
    fwrite($fp, $content);//写入文件
    fclose($fp);//关闭资源通道
}

/**
 * 返回当前  模块-控制器-方法 拼接
 * by J.sky
 * 2018年7月24日14:33:54
 * @return string
 */
function retMAC()
{
    return request()->module() . '-' . request()->controller() . '-' . request()->action();
}

/**
 * 获取树形结构数据
 * @param $list
 * @param int $id
 * @return array
 */
function getChild($list, $id = 0)
{
    //初始化数组
    $child = [];
    //循环数据源
    foreach ($list as $key => $value) {
        //判断父级ID是否等于传递过来的ID
        if ($value['father'] == $id) {
            //如果等于先保存下来
            $child[$key] = $value;
            //把自己排除在外
            unset($list[$key]);
            //继续去找子级
            $childs = getChild($list, $value['id']);
            if (!empty($childs)) {
                $child[$key]['children'] = $childs;
            }
        }
    }
    //返回数据
    return array_values($child);
}

/**
 * 导出Excel
 * @param object $spreadsheet 数据
 * @param string $format 格式:excel2003 = xls, excel2007 = xlsx
 * @param string $savename 保存的文件名
 * @return filedownload         浏览器下载
 */
function exportExcel($spreadsheet, $format = 'xls', $savename = 'export')
{

    if (!$spreadsheet) return false;
    if ($format == 'xls') {
        //输出Excel03版本
        header('Content-Type:application/vnd.ms-excel');
        $class = "\PhpOffice\PhpSpreadsheet\Writer\Xls";
    } elseif ($format == 'xlsx') {
        //输出07Excel版本
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $class = "\PhpOffice\PhpSpreadsheet\Writer\Xlsx";
    }

    //输出名称
    header('Content-Disposition: attachment;filename="' . $savename . '.' . $format . '"');

    //禁止缓存
    header('Cache-Control: max-age=0');
    $writer = new $class($spreadsheet);
    $filePath = env('runtime_path') . "temp/" . time() . microtime(true) . ".tmp";
    if (!file_exists($filePath)) {
        if (!is_dir(env("runtime_path") . "temp/")) {
            $res = mkdir(env("runtime_path") . "temp/", 0777, true);
        }

        fopen($filePath, "w");
    }
    $writer->save($filePath);
    //die;
    readfile($filePath);

    unlink($filePath);
}

/**
 * object数据 转 array数组
 * @param $array 需要转换的数组
 * @return array
 */
function object_array($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}
